package com.android.fragmentdemo.thread11

import org.junit.Test
import java.util.concurrent.locks.ReentrantLock

class Demo11 {
    @Test
    fun testRunnable() {
        val runnable = DefineRunnable()
        val thread1 = Thread(runnable)
        val thread2 = Thread(runnable)

        thread1.start()
        thread2.start()

        thread1.join()
        thread2.join()

        Thread.sleep(10 * 1000)
        println("result:${runnable.count}")
    }

    class DefineRunnable : Runnable {
        var count = 0
        private val reentrantLock = ReentrantLock()
        override fun run() {
            for (i in 0.until(1000 * 1000)) {
                reentrantLock.lock()
                try {
                    count++
                } finally {
                    reentrantLock.unlock()
                }
            }
        }
    }

}